// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { roomId, status, gameData } = event
  
  try {
    // 查找房间
    const room = await db.collection('rooms').where({
      roomId: roomId
    }).get()
    
    if (room.data.length === 0) {
      return {
        success: false,
        error: '房间不存在'
      }
    }
    
    const roomData = room.data[0]
    
    // 检查操作权限
    if (roomData.creator !== wxContext.OPENID) {
      return {
        success: false,
        error: '无权限操作'
      }
    }
    
    // 更新房间状态
    const updateData = {
      status: status,
      lastUpdateTime: db.serverDate()
    }
    
    // 如果提供了游戏数据，则更新
    if (gameData) {
      updateData.gameData = gameData
    }
    
    await db.collection('rooms').where({
      roomId: roomId
    }).update({
      data: updateData
    })
    
    return {
      success: true,
      roomData: {
        ...roomData,
        ...updateData
      }
    }
  } catch (error) {
    console.error('更新房间状态失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 